package com.kehutong.payfees.admin;

import java.util.ArrayList;
import java.util.List;

import com.kehutong.payfees.entity.*;
import org.coraframework.authz.HasPermission;
import org.coraframework.converter.util.StringUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.util.Enums;

import com.kehutong.payfees.enums.FeesType;
import org.coraframework.util.Objects;

/**
 * 收费科目
 * 水费、电费 自定义
 */
@MvcAction
@ReqMapping("/admin/charge/fee_type")
public class ChargeFeeTypeAction {
	
	@Inject
	private JdbcSession jdbcSession;

    @Bean(newInstance=true, copy=true)
    @HasPermission("charge:feetype:edit")
    @ReqMapping("/save")
    public Object save(ChargeFeeType item) {
        if (StringUtil.isBlank(item.getName())) {
            return Result.error(0, "名称不能为空");
        }

        if (existSameName(item)) {
            return Result.error(0, item.getName() + "已存在，请勿重复添加");
        }

        item.setFeetype(Enums.getEnum(FeesType.class, item.getType()));

        jdbcSession.insert(item);
        return Result.success();
    }

    /**
     * 是否存在重名
     */
    private boolean existSameName(ChargeFeeType feeType) {
        return !jdbcSession.findArray(ChargeFeeType.class)
                .eq("name", feeType.getName())
                // 传入的entity已携带id
                .noEq("id", feeType.getId())
                .exe().isEmpty();
    }

    @HasPermission("charge:feetype:edit")
    @ReqMapping("/delete")
    public Object delete(ChargeFeeType feeType) {
        List<ChargeTemplate> templates = jdbcSession.findArray(ChargeTemplate.class)
                .like("items", feeType.getId())
                .eq("deleted", false)
                .exe();

        if(templates.size() > 0){
           return Result.error(0, "[" + feeType.getName() + "]已配置收费模板,请先修改模板配置");
        }else{
            jdbcSession.deleteById(feeType);
        }

        return Result.success();
    }

    @Bean(copy=true)
    @HasPermission("charge:feetype:edit")
    @ReqMapping("/update")
    public Object update(ChargeFeeType item) {
        if (StringUtil.isBlank(item.getName())) {
            return Result.error(0, "名称不能为空");
        }

        if (existSameName(item)) {
            return Result.error(0, item.getName() + "已存在，请勿重复添加");
        }

        item.setFeetype(Enums.getEnum(FeesType.class, item.getType()));

        jdbcSession.updateById(item);

        List<ChargeSundry> sundrys = jdbcSession.findArray(ChargeSundry.class)
                .eq("feeTypeId", item.getId())
                .exe();

        if(Objects.nonNull(item.getFeetype())){
            sundrys.forEach(sundry ->{
                sundry.setFeeType(item.getFeetype().getDesc());
                jdbcSession.updateById(sundry);
            });
        }

        List<ChargeStandard> standards = jdbcSession.findArray(ChargeStandard.class)
                .eq("feeTypeId", item.getId())
                .exe();
        standards.forEach(standard -> {
            standard.setFeeTypeName(item.getName());
            jdbcSession.updateById(standard);
        });

        List<ChargeChoose> chooses = jdbcSession.findArray(ChargeChoose.class)
                .eq("feeTypeId", item.getId())
                .exe();
        chooses.forEach(choose -> {
            choose.setFeeTypeName(item.getName());
            jdbcSession.updateById(choose);
        });

        return Result.success();
    }

    /**
     * 不分页一次性加载
     */
    @HasPermission("charge:feetype:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {
        List<ChargeFeeType> types = jdbcSession.findArray(ChargeFeeType.class)
                .eq(jsonObject, "feetype")
                .like(jsonObject, "name")
                .order("createTime", "DESC")
                .exe();

        return Result.success(types);
    }

    @HasPermission("charge:feetype:view")
    @ReqMapping("/tree")
    public Object tree(JSONObject jsonObject) {
        final List<ChargeFeeType> list = jdbcSession.findArray(ChargeFeeType.class)
                .like(jsonObject, "name")
                .order("createTime", "DESC")
                .exe();

        final ChargeFeeType root = Pool.newInstance(ChargeFeeType.class, "0");
        List<ChargeFeeType> childList = new ArrayList<>();
        for (FeesType type :FeesType.values()) {
            if(type != FeesType.TEMPORARY) {
                ChargeFeeType item = Pool.newInstance(ChargeFeeType.class, type.getId());
                item.setName(type.getDesc());
                List<ChargeFeeType> itemChildList = new ArrayList<>();
                for (ChargeFeeType feeType : list) {
                    if (Objects.nonNull(feeType.getFeetype()) &&
                            feeType.getFeetype().getId().equals(type.getId())) {
                        feeType.setDisabled(true);
                        itemChildList.add(feeType);
                    }
                }
                item.setChildList(itemChildList);
                childList.add(item);
            }
        }
        root.setChildList(childList);

        return Result.success(root);
    }

    /**
     * 分页加载
     * @throws Exception 
     */
    @HasPermission("charge:feetype:view")
    @ReqMapping("/page")
    public Object page(JSONObject jsonObject) throws Exception {
        return jdbcSession.findPage(ChargeFeeType.class)
        		.eq(jsonObject, "feetype")
                .like(jsonObject, "name")
                .order("createTime", "DESC")
                .page(jsonObject)
                .exe();
    }

    @ReqMapping("/get")
    public Object get(ChargeFeeType item) {
        return Result.success(item);
    }

}
